<?php

namespace app\commission;

use app\models\order\Order as Model;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\user\User;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\services\Chain;
use app\util\Debug;

class Order
{
    public function commission(Model $order)
    {
        $transaction = \Yii::$app->db->beginTransaction();

        try {

            $first_order_item = OrderItem::find()
                ->where(['order_id' => $order->id])
                ->orderBy(['id' => SORT_ASC])
                ->limit(1)
                ->one();

            $product_id = $first_order_item->product_id;

            // bao area
            if (ProductAreaList::checkInArea($product_id, Product::$areaMap['BAO'])) {
                $this->baoArea($order);
            }

            // brand area
            if (ProductAreaList::checkInArea($product_id, Product::$areaMap['BRAND'])) {
                $this->brandArea($order);

                // sale return
                $order->return_sale = 1;
                $order->save();

                // sale commission
                $sale = new Sale($order);
                $sale->run();
            }

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            Debug::commission('order-fail', $e->getMessage());
        }
    }

    // 爆品区
    private function baoArea(Model $order)
    {
        /*
         * 没有减掉成本, 否则循环order_item => product 计算成本
         *
         * 使用了"蜜易券"就不返了
         *
         * 1) 返积分
         * 2) 返购物券
         */

        if ($order->use_platform_ticket == 0) {

            $total = $order->total_pay - $order->total_freight;

            $model = new UserCommission();
            $model->user_id = $order->user_id;
            $model->fans_id = $order->user_id;
            $model->order_id = $order->id;
            $model->score = $total;
            $model->ticket = $total;
            $model->status = 1;
            $model->award_name = UserCommission::$AWARD_NAME['BAO_AREA'];
            $model->award_type = UserCommission::$AWARD_Type['BAO_AREA'];
            $model->save();

            Commission::getInstance()->commissionSaveAccount($model);
        }
    }

    // 品牌区
    private function brandArea(Model $order)
    {
        /*
         * 直推
         * 销售(业绩)奖励
         * 团队奖
         * 平级奖
         */
        $this->firstRecommend($order);
        $this->saleReset($order);
        $this->team($order);
        // $this->equal($order);
    }

    private function firstRecommend(Model $order)
    {
        // $ratio = 0.2;
        $ratio = 0.33;

        $total = $order->total_pay - $order->total_freight;
        $referrer = Chain::getReferrer($order->user_id, true);

        if ($referrer && $referrer->level >= UserLevel::$keys['svip1']) {
            $model = new UserCommission();
            $model->user_id = $referrer->id;
            $model->fans_id = $order->user_id;
            $model->balance = $total * $ratio;
            $model->status = 1;
            $model->order_id = $order->id;
            $model->award_name = UserCommission::$AWARD_NAME['RECOMMEND'];
            $model->award_type = UserCommission::$AWARD_Type['RECOMMEND'];
            $model->save();

            Commission::getInstance()->commissionSaveAccount($model);
        }
    }

    private function saleReset(Model $order)
    {
        // warn: crontab

        $user = User::findOne(['id' => $order->user_id]);
        if ($user->reset_sale == 1) {
            // reset sale
            // $user->order_amount = 0;
            // $user->sale_commission = 0;
            $user->reset_sale = 0;
            $user->save();
        }
    }

    private function team(Model $order)
    {
        $total = $order->total_pay - $order->total_freight;

        $ratio1 = 0.01;
        $ratio2 = 0.03;
        $ratio3 = 0.045;

        $use_ratio = 0;

        $has_1 = false;
        $has_2 = false;

        $referrers = Chain::getReferrerChain($order->user_id);

        foreach ($referrers as $v) {
            if ($v['level'] >= UserLevel::$keys['w3']) {
                $balance = $total * ($ratio3 - $use_ratio);
                $this->saveTeam($v['id'], $balance, $order);
                break;
            }
            if (!$has_2 && $v['level'] == UserLevel::$keys['w2']) {
                $balance = $total * ($ratio2 - $use_ratio);
                $use_ratio = $ratio2;
                $this->saveTeam($v['id'], $balance, $order);
                $has_2 = true;
            }
            if (!$has_1 && $v['level'] == UserLevel::$keys['w1']) {
                $balance = $total * $ratio1;
                $use_ratio = $ratio1;
                $this->saveTeam($v['id'], $balance, $order);
                $has_1 = true;
            }
        }
    }

    private function saveTeam($user_id, $balance, $order)
    {
        if ($balance > 0) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $order->user_id;
            $model->balance = $balance;
            $model->status = 1;
            $model->order_id = $order->id;
            $model->award_name = UserCommission::$AWARD_NAME['TEAM'];
            $model->award_type = UserCommission::$AWARD_Type['TEAM'];
            $model->save();

            Commission::getInstance()->commissionSaveAccount($model);

            // 平级奖是根据团队奖来的
            $this->equal($order, $user_id);
        }
    }

    // private function equal(Model $order)
    // {
    //     $total = $order->total_pay - $order->total_freight;
    //
    //     $ratio1 = 0.005;
    //     $ratio2 = 0.015;
    //     $ratio3 = 0.025;
    //
    //     $user = User::findOne(['id' => $order->user_id]);
    //     if ($user->level >= UserLevel::$keys['w1']) {
    //         $referrers = Chain::getReferrerChain($order->user_id, [
    //             UserLevel::$keys['w1'],
    //             UserLevel::$keys['w2'],
    //             UserLevel::$keys['w3']
    //         ]);
    //
    //         if ($referrers) {
    //             $ratio = 0;
    //             switch ($user->level) {
    //                 case UserLevel::$keys['w1']:
    //                     $ratio = $ratio1;
    //                     break;
    //                 case UserLevel::$keys['w2']:
    //                     $ratio = $ratio2;
    //                     break;
    //                 case UserLevel::$keys['w3']:
    //                     $ratio = $ratio3;
    //                     break;
    //             }
    //
    //             $balance = $total * $ratio;
    //
    //             foreach ($referrers as $v) {
    //                 if ($v['level'] == $user->level) {
    //                     $this->saveEqual($v['id'], $balance, $order);
    //                     break;
    //                 }
    //             }
    //         }
    //     }
    // }

    private function equal(Model $order, $user_id)
    {
        $total = $order->total_pay - $order->total_freight;

        $ratio1 = 0.005;
        $ratio2 = 0.015;
        $ratio3 = 0.025;

        // $user = User::findOne(['id' => $order->user_id]);
        $user = User::findOne(['id' => $user_id]);
        $referrers = Chain::getReferrerChain($user->id, [
            // UserLevel::$keys['w1'],
            // UserLevel::$keys['w2'],
            // UserLevel::$keys['w3']
            $user->level
        ]);

        if ($referrers) {
            $ratio = 0;
            // 只返第一个
            $referrer = $referrers[0];
            switch ($referrer['level']) {
                case UserLevel::$keys['w1']:
                    $ratio = $ratio1;
                    break;
                case UserLevel::$keys['w2']:
                    $ratio = $ratio2;
                    break;
                case UserLevel::$keys['w3']:
                    $ratio = $ratio3;
                    break;
            }

            $balance = $total * $ratio;
            $this->saveEqual($referrer['id'], $balance, $order);

            // foreach ($referrers as $v) {
            //     if ($v['level'] == $user->level) {
            //         $this->saveEqual($v['id'], $balance, $order);
            //         break;
            //     }
            // }
        }
    }

    private function saveEqual($user_id, $balance, $order)
    {
        if ($balance > 0) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $order->user_id;
            $model->balance = $balance;
            $model->status = 1;
            $model->order_id = $order->id;
            $model->award_name = UserCommission::$AWARD_NAME['EQUAL'];
            $model->award_type = UserCommission::$AWARD_Type['EQUAL'];
            $model->save();

            Commission::getInstance()->commissionSaveAccount($model);
        }
    }

}